package config;


import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.util.Map;

import tools.AppContext;
import tools.GsonTools;
import tools.Logger;


public class ApiClient {
	public final static String TIMEOUT_ERROR = "服务器无法连接或处理超时";//无法连接或处理超时
	public final static String SERVER_BIZ_ERROR = "服务器应用程序运行异常";//后台应用程序报错
	public final static String APP_BIZ_ERROR = "APP业务处理异常";//APP内业务处理异常
	private static AsyncHttpClient client = new AsyncHttpClient();



	public interface ClientCallback {
		abstract void onSuccess(Object data);
		abstract void onFailure(String message);
	}
	private static String getAbsoluteUrl(String relativeUrl) {
		client.setTimeout(35*1000);
		client.setMaxConnections(5);
		return CommonValue.BASE_API + CommonValue.URL_PREFIX + relativeUrl;
	}


	/** 虚拟账户支付查询账户
	 * @param params
	 * @param callback
	 */
	public static void getByCustomerNo(RequestParams params, final ClientCallback callback ){
		QYRestClient.cardPost("getByCustomerNo.do",params, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
				String res = new String(responseBody);
				try {
					Map<String, Object> customerStr = ((Map<String, Object>) JSON.parse(res));
					if (customerStr.get("result").equals("fail")){
						callback.onFailure(customerStr.get("message").toString());
					}else {
						callback.onSuccess(JSON.parse(customerStr.toString()));
					}
				} catch (Exception e) {
					Logger.e(e);
					callback.onFailure(APP_BIZ_ERROR);
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable throwable) {
				callback.onFailure(statusCode == 0 ? TIMEOUT_ERROR : SERVER_BIZ_ERROR);
			}
		});
	}
	/**
	 * 支付宝查询接口
	 * @param params
	 * @param callback
	 */
	public static void alipayQuery( RequestParams params, final ClientCallback callback) {
		QYRestClient.post("queryOrder.do", params, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
				String res = new String(responseBody);
				try {
					Map<String, String> stringStringMap = GsonTools.parseToMap(res);
					callback.onSuccess(stringStringMap);
				} catch (Exception e) {
					Logger.e(e);
					callback.onFailure(APP_BIZ_ERROR);
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
				callback.onFailure(statusCode == 0 ? TIMEOUT_ERROR : SERVER_BIZ_ERROR);
			}
		});
	}
}



